<template>
    <!-- 编辑弹窗 -->
    <el-dialog title="编辑头像" width="800" :append-to-body="true" v-model="editDialogRef">
        <!-- 截图预览 -->
        <div class="preContent">
            <img :src="previewUrl" alt="用户头像预览图" class="preImg" />
        </div>
        <template #footer>
            <div class="dialogFooter">
                <el-button @click="cancleEditAvatar">取消</el-button>
                <UploadFile :isEndUpload="isEndUpload" :uploadType="'avatar'">
                    <el-button type="primary">选择图片</el-button>
                </UploadFile>
                <el-button type="primary" @click="uploadAvatar">确认修改</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { reqEditAvatar } from '@/api/user'
import type { editAvatarFormData } from '@/api/user/type'
import { readBlobAsBase64 } from '@/utils/chatfile'

const userStore = useUserStore()
const editDialogRef = defineModel()
// 判断用户是否结束上传操作
const isEndUpload = ref<boolean>(false)
// 用户选择的文件
let selectedImg = reactive<editAvatarFormData>({
    userId: -1,
    newAvatar: null,
})
// 预览头像的url
let previewUrl = ref<string>(userStore.avatar)

// 取消修改头像
const cancleEditAvatar = () => {
    editDialogRef.value = false
    isEndUpload.value = true
    userStore.changeAvatar = null
}

// 上传头像
const uploadAvatar = async () => {
    if (selectedImg.newAvatar) {
        const result = await reqEditAvatar(selectedImg)
        if (result.code == 200) {
            userStore.avatar = result.data
            ElMessage.success('头像修改成功')
        } else {
            ElMessage.error(result.message)
        }
        selectedImg.userId = -1
        selectedImg.newAvatar = null
    } else {
        ElMessage.success('保留原头像成功')
    }
    editDialogRef.value = false
    isEndUpload.value = true
    userStore.changeAvatar = null
}

watch(
    () => userStore.changeAvatar,
    async (newVal) => {
        if (newVal) {
            isEndUpload.value = false
            selectedImg.userId = userStore.userId
            selectedImg.newAvatar = await readBlobAsBase64(newVal.fileData as Blob)
            previewUrl.value = URL.createObjectURL(newVal.fileData as Blob)
        }
    },
    { deep: true },
)
</script>

<style scoped lang="scss">
.preContent {
    width: 100%;
    height: 400px;
    background: url('../../../public/file-images/mosaic.png');
    @include flex-layout(flex, center, center);

    .preImg {
        max-width: 100%;
        max-height: 100%;
    }
}

.dialogFooter {
    @include flex-layout(flex, normal, normal, nowrap, row-reverse);

    .el-button {
        margin-left: 12px;
    }
}
</style>
